package ${package.Controller};

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.samuel.basics.enums.ResultEnum;
import com.samuel.basics.exception.CustomException;
import com.samuel.basics.constant.CommonConstant;
import com.samuel.basics.constant.OperateConstant;
import com.samuel.basics.exception.ViewException;
import com.samuel.basics.annotation.CacheLock;
import com.samuel.basics.annotation.OperateLog;
import org.apache.commons.lang3.StringUtils;

<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
import javax.annotation.Resource;

import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
import java.time.LocalDateTime;
import java.util.Arrays;


/**
* <p>
* ${cfg.context.bizChName}-前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/

<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/${cfg.context.bizEnName}")
<#if kotlin>
public class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>

    private static final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);

    @Resource
    private ${table.serviceName} ${cfg.context.bizEnName}Service;

    private final static String PREFIX = "${cfg.context.bizEnName}/";

    /**
    * 跳转到${cfg.context.bizChName}首页 ${(package.ModuleName)!'1000'} ==> <#if package.ModuleName??>/${package.ModuleName}</#if>/${cfg.context.bizEnName}
    */
    @GetMapping("/list")
    public String list() {
        return PREFIX + LIST;
    }

    @ResponseBody
    @GetMapping("/listJson")
    @OperateLog(operateModule = "${cfg.context.bizChName}", operateType = OperateConstant.SELECT, operateDesc = "查询${cfg.context.bizChName}列表")
    public JSONObject listJson(Page<${entity}> iPage, ${entity} ${cfg.context.bizEnName}Entity) {
        QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
        iPage = ${cfg.context.bizEnName}Service.page(iPage, queryWrapper);
        return page2LayUiTablePage(iPage);
    }

    @GetMapping("/view")
    @OperateLog(operateModule = "${cfg.context.bizChName}", operateType = OperateConstant.VIEW, operateDesc = "查看${cfg.context.bizChName}详情")
    public String view(String id, ModelMap modelMap) {
        if (StringUtils.isBlank(id)) {
            throw new CustomException(ResultEnum.GET_ERROR, "id不存在");
        }
        ${entity} ${cfg.context.bizEnName}Entity = ${cfg.context.bizEnName}Service.getById(id);
        modelMap.put("${cfg.context.bizEnName}Entity", ${cfg.context.bizEnName}Entity);
        return PREFIX + VIEW;
    }

    @GetMapping("update")
    @OperateLog(operateModule = "${cfg.context.bizChName}", operateType = OperateConstant.VIEW, operateDesc = "进入修改${cfg.context.bizChName}信息页面")
    public String toUpdate(String id, ModelMap modelMap) {
        if (StringUtils.isBlank(id)) {
            throw new CustomException(ResultEnum.GET_ERROR, "请选择一条数据！");
        }

        ${entity} ${cfg.context.bizEnName}Entity = ${cfg.context.bizEnName}Service.getById(id);
        if (${cfg.context.bizEnName}Entity == null) {
            logger.info("查询不到数据！");
            throw new RuntimeException("请选择一条数据！");
        }
        modelMap.put("${cfg.context.bizEnName}Entity", ${cfg.context.bizEnName}Entity);
        return PREFIX + INPUT;
    }

    @ResponseBody
    @PostMapping("/update")
    @CacheLock(prefix = "${cfg.context.bizEnName}-update")
    @OperateLog(operateModule = "${cfg.context.bizChName}", operateType = OperateConstant.UPDATE, operateDesc = "修改${cfg.context.bizChName}信息")
    public JSONObject update(${entity} ${cfg.context.bizEnName}Entity) {
        JSONObject jsonObject = validate(${cfg.context.bizEnName}Entity, CommonConstant.DATA_UPDATE_TYPE);
        Integer code = jsonObject.getInteger(CommonConstant.AjaxCode.CODE);
        if (code.equals(CommonConstant.AjaxCode.FAIL_CODE)) {
            return jsonObject;
        }

        jsonObject = new JSONObject();
        boolean flag = ${cfg.context.bizEnName}Service.updateById(${cfg.context.bizEnName}Entity);
        if (flag) {
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "修改${cfg.context.bizChName}数据成功！");
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
        } else {
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "修改${cfg.context.bizChName}数据失败！");
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
        }
        return jsonObject;
    }

    @GetMapping("save")
    @OperateLog(operateModule = "${cfg.context.bizChName}", operateType = OperateConstant.VIEW, operateDesc = "跳转保存${cfg.context.bizChName}信息页面")
    public String toSave() {
        return PREFIX + INPUT;
    }

    @ResponseBody
    @PostMapping("save")
    @CacheLock(prefix = "${cfg.context.bizEnName}-save")
    @OperateLog(operateModule = "${cfg.context.bizChName}", operateType = OperateConstant.SAVE, operateDesc = "保存${cfg.context.bizChName}信息")
    public JSONObject save(${entity} ${cfg.context.bizEnName}Entity) {
        JSONObject jsonObject = validate(${cfg.context.bizEnName}Entity, CommonConstant.DATA_SAVE_TYPE);
        Integer code = jsonObject.getInteger(CommonConstant.AjaxCode.CODE);
        if (code.equals(CommonConstant.AjaxCode.FAIL_CODE)) {
            return jsonObject;
        }
        jsonObject = new JSONObject();
        try {
            ${cfg.context.bizEnName}Entity.setCreateDate(LocalDateTime.now());
            ${cfg.context.bizEnName}Service.save(${cfg.context.bizEnName}Entity);
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "保存数据成功！");
        } catch (Exception e) {
            logger.error("保存${cfg.context.bizChName}数据异常！原因：{}", e.getMessage());
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, e.getMessage());
        }
        return jsonObject;
    }

    /**
    * 批量删除
    *
    * @param ids id集合
    */
    @ResponseBody
    @PostMapping("delete")
    @CacheLock(prefix = "${cfg.context.bizEnName}-delete")
    @OperateLog(operateModule = "${cfg.context.bizChName}", operateType = OperateConstant.DELETE, operateDesc = "删除${cfg.context.bizChName}信息，可批量删除！")
    public JSONObject delete(String ids) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isEmpty(ids)) {
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "请至少选择一条数据！");
            return jsonObject;
        }
        try {
            ${cfg.context.bizEnName}Service.removeByIds(Arrays.asList(ids.split(CommonConstant.DOC_FLAG)));
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "删除${cfg.context.bizChName}数据成功！");
        } catch (Exception e) {
            logger.error("删除失败！原因： {}", e.getMessage());
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "删除${cfg.context.bizChName}数据失败！");
        }

        return jsonObject;
    }

    protected JSONObject validate(${entity} ${cfg.context.bizEnName}Entity, int type) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
        if (${cfg.context.bizEnName}Entity == null) {
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "对象不能为空！");
            return jsonObject;
        }

        if (type == CommonConstant.DATA_UPDATE_TYPE) {
            if (StringUtils.isEmpty(${cfg.context.bizEnName}Entity.getId())) {
                jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "请至少选择一个对象数据！");
                return jsonObject;
            }
            // 判断${cfg.context.bizChName}是否存在
            ${entity} ${cfg.context.bizEnName} = ${cfg.context.bizEnName}Service.getById(${cfg.context.bizEnName}Entity.getId());
            if (${cfg.context.bizEnName} == null) {
                jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "该数据被删除，已经不存在！");
                return jsonObject;
            }

        } else if (type == CommonConstant.DATA_SAVE_TYPE) {

        } else {
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "数据类型错误！");
            return jsonObject;
        }
        jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
        jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "数据验证成功！");
        return jsonObject;
    }

}
</#if>
